package org.zhq.core.schedule;

import org.zhq.core.Connector;
import org.zhq.core.ScheduleTask;

import java.util.concurrent.TimeUnit;

/**
 * @author zhengquan
 * @date 2019/2/24
 */
public class IdleTimeoutScheduleTask extends ScheduleTask {
    public IdleTimeoutScheduleTask(long idleTimeout, TimeUnit unit, Connector connector) {
        super(idleTimeout, unit, connector);
    }


    @Override
    public void run() {

        long lastActiveTime = connector.getLastActiveTime();
        long idleTimeoutMilliseconds = this.idleTimeoutMilliseconds;

        long nextDelay = idleTimeoutMilliseconds - (System.currentTimeMillis() - lastActiveTime);

        if(nextDelay<=0){
            schedule(idleTimeoutMilliseconds);
            try {
                connector.fireIdleTimeoutEvent();
            }catch (Throwable throwable){
                connector.fireExceptionCaught(throwable);
            }
        }else{
            schedule(nextDelay);
        }
    }
}

